<?php
class lettersclass {

	function lettersclass() {
		global $setupdata, $mysqlclass;
		$this->setupdata=$setupdata;
		$this->mysqlclass=$mysqlclass;
	}
	
	function jobs_rename($name, $job_id, $source_type_html, $source_type_text){
		$name = trim($name);	
		$name = addslashes($name);
		$this->mysqlclass->mysql_my_query("UPDATE `".$this->setupdata['table_prefix']."letters` SET `name`='".$name."', `tempalate_html`='".$source_type_html."', `tempalate_text`='".$source_type_text."' WHERE ".$job_id."=`id`", __LINE__, __FILE__);	
	}
	
	function get_all_source_types(){
		$result = array();
		if (isset($this->setupdata['smarty_guest_mail_template_dir']) && (strlen($this->setupdata['smarty_guest_mail_template_dir']) > 0)){
			if (file_exists($this->setupdata['smarty_guest_mail_template_dir'])) $dir = dir($this->setupdata['smarty_guest_mail_template_dir']);
			else return $result;
		} else {
			if (file_exists("templates/guest/newsletters")) $dir = dir("templates/guest/newsletters");
			else return $result;
		}
		while (false !== ($file = $dir->read())) {
			if ($file != '.' && $file != '..') {
				if (!is_dir($file)) $result[$file] = $file;
			}
		}
		$dir->close();
		asort($result);
		return $result;
	}
	
	function jobs_add($name, $type_html, $type_text){
		$name = trim($name);	
		$name = addslashes($name);
		$sql = $this->mysqlclass->mysql_my_query("INSERT INTO `".$this->setupdata['table_prefix']."letters` (`id`,`name`,`letters_subject`,`letters_from`,`letters_title`,`letters_header`,`letters_footer`,`letters_unsubscribe`,`tempalate_html`,`tempalate_text`,`source_type`,`source_name`,`html`,`text`,`date_create`,`date_start`,`date_end`,`author`,`sender`) VALUES ('', '".$name."', '', '', '', '', '', '', '".$type_html."', '".$type_text."', '', '', '', '', '".date("YmdHis")."', '', '', ".$_SESSION['login_user'].", 0)", __LINE__, __FILE__);
	}
	
	function jobs_del($arr){
		foreach($arr as $elem){
			if (isset($elem) and ($elem > 0)){
				$sql = $this->mysqlclass->mysql_my_query("DELETE FROM `".$this->setupdata['table_prefix']."letters` WHERE ".$elem." = `id`", __LINE__, __FILE__);		
				$sql = $this->mysqlclass->mysql_my_query("DELETE FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE ".$elem." = `parent`", __LINE__, __FILE__);		
			}
		}
	}
	
	function get_all_jobs(){
		$result = array();
		$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters`", __LINE__, __FILE__);	
		while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
			$row['name'] = stripslashes($row['name']);
			$result[$row['id']] = $row;
		}
		return $result;
	}
		
	function get_job_data($job_id){
		$result = array();
		$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters` WHERE ".$job_id." = `id`", __LINE__, __FILE__);	
		if (mysql_num_rows($sql) > 0) {
			$row = mysql_fetch_array($sql, MYSQL_ASSOC);
			$row['name'] = stripslashes($row['name']);
			$row['letters_subject'] = stripslashes($row['letters_subject']);
			$row['letters_title'] = stripslashes($row['letters_title']);
			$row['letters_header'] = stripslashes($row['letters_header']);
			$row['letters_footer'] = stripslashes($row['letters_footer']);
			$row['letters_unsubscribe'] = stripslashes($row['letters_unsubscribe']);
			$row['html'] = stripslashes($row['html']);
			$row['text'] = stripslashes($row['text']);
			if ($row['source_type'] == "clients"){
				$row['source_name'] = explode(";", substr($row['source_name'], 0, strlen($row['source_name'])-1));
				foreach($row['source_name'] as $key=>$value) $row['source_name1'][$value] = $value;
				$row['source_name'] = $row['source_name1'];
				unset($row['source_name1']);
			}
			$result = $row;
		}
		return $result;
	}
	
	function jobs_mod($job_id, $job_html, $job_text, $job_subject, $job_from, $job_title, $job_header, $job_footer, $job_unsubscribe){
		$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters` WHERE ".$job_id." = `id`", __LINE__, __FILE__);	
		if (mysql_num_rows($sql) > 0) {
			$job_subject = addslashes($job_subject);
			$job_html = addslashes($job_html);
			$job_text = addslashes($job_text);
			$job_title = addslashes($job_title);
			$job_header = addslashes($job_header);
			$job_footer = addslashes($job_footer);
			$job_unsubscribe = addslashes($job_unsubscribe);
			//if (!eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $job_from)) $job_from = "";
			$this->mysqlclass->mysql_my_query("UPDATE `".$this->setupdata['table_prefix']."letters` SET `text`='".$job_text."', `html`='".$job_html."', `letters_subject`='".$job_subject."', `letters_from`='".$job_from."', `letters_title`='".$job_title."', `letters_header`='".$job_header."', `letters_footer`='".$job_footer."', `letters_unsubscribe`='".$job_unsubscribe."' WHERE ".$job_id." = `id`", __LINE__, __FILE__);
		}
	}
	
	function job_emails_import($job_id, $job_source_type, $job_source_name){
		$emails = array();
		$this->mysqlclass->mysql_my_query("UPDATE `".$this->setupdata['table_prefix']."letters` SET `date_end`='0000-00-00 00:00:00', `date_start`='0000-00-00 00:00:00', `source_type`='".$job_source_type."'  WHERE ".$job_id."=`id`", __LINE__, __FILE__);
		$sql = $this->mysqlclass->mysql_my_query("DELETE FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE ".$job_id." = `parent`", __LINE__, __FILE__);
		if ($job_source_type == "files"){
			$emails=file($job_source_name['tmp_name']);
			$job_source_name = $job_source_name['name'];
		} elseif ($job_source_type == "clients") {
			global $clientsclass;
			$group_ids = "";
			foreach($job_source_name as $group_id){
				$group_ids .= $group_id.";";
				if ((int) $group_id > 0) {
					$array = $clientsclass->get_clients_info_by_group_id($group_id);
					foreach($array as $elem){
						if ((isset($elem['main']['email'])) && (strlen($elem['main']['email']) > 0)) $emails[] = $elem['main']['email'];
					}
				}
			}
			$this->mysqlclass->mysql_my_query("UPDATE `".$this->setupdata['table_prefix']."letters` SET `source_name`='".$group_ids."' WHERE ".$job_id."=`id`", __LINE__, __FILE__);
		} elseif ($job_source_type == "subscribe_news") {
			$sql = $this->mysqlclass->mysql_my_query("SELECT `email` FROM `".$this->setupdata['table_prefix']."subscribe_news` ORDER BY `regdate` DESC", __LINE__, __FILE__);
			while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) $emails[] = $row['email'];
		} elseif ($job_source_type == "textfield") {
			$emails = explode("\n", $job_source_name);
		}
		
		if (count($emails) > 0){
			foreach($emails as $email){
				$email = trim($email);
				if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email)){
					$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE ".$job_id."=`parent` AND `email`='".$email."'", __LINE__, __FILE__);
					if (mysql_num_rows($sql) < 1) {
						$sql2 = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters_emails_unsub` WHERE '".$email."'=`email`", __LINE__, __FILE__);
						if (mysql_num_rows($sql2) < 1) {
							$sql = $this->mysqlclass->mysql_my_query("INSERT INTO `".$this->setupdata['table_prefix']."letters_jobs` (`id`,`parent`,`email`) VALUES ('', ".$job_id.", '".$email."')", __LINE__, __FILE__);
						} else {
							// 
						}
					}
					$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters_emails` WHERE `email`='".$email."'", __LINE__, __FILE__);
					if (mysql_num_rows($sql) < 1) $this->mysqlclass->mysql_my_query("INSERT INTO `".$this->setupdata['table_prefix']."letters_emails` (`email`) VALUES ('".$email."')", __LINE__, __FILE__);
				}
			}
		}
	}
	
	function get_job_emails_count($job_id){
		$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE ".$job_id."=`parent`", __LINE__, __FILE__);			
		return mysql_num_rows($sql);
	}
	
	function get_job_status($job_id){
		$load = array();
		$sql = $this->mysqlclass->mysql_my_query("SELECT COUNT(`id`) FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE `status`=1 AND ".$job_id."=`parent`", __LINE__, __FILE__);			
		$row = mysql_fetch_array($sql);
		$load['sended'] = $row[0];
		$sql = $this->mysqlclass->mysql_my_query("SELECT COUNT(`id`) FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE `status`=0 AND ".$job_id."=`parent`", __LINE__, __FILE__);			
		$row = mysql_fetch_array($sql);
		$load['notsended'] = $row[0];
		return $load;
	}
	
	function get_job_emails($job_id, $param){
		$load = array();
		if ($param == 1) $sql = $this->mysqlclass->mysql_my_query("SELECT `email` FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE ".$job_id."=`parent` ORDER BY `email` ASC", __LINE__, __FILE__);			
		else  $sql = $this->mysqlclass->mysql_my_query("SELECT `email` FROM `".$this->setupdata['table_prefix']."letters_jobs` WHERE ".$job_id."=`parent` AND `status`=0 ORDER BY `email` ASC", __LINE__, __FILE__);			
		while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) $load[] = $row['email'];
		return $load;
	}
	
	function get_blacklist(){
		$load = array();
		$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters_emails_unsub`", __LINE__, __FILE__);			
		while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) $load[] = $row;
		return $load;
	}
	
	function email_del_from_blacklist($del_mas){
		foreach($del_mas as $elem){
			if (isset($elem) and ($elem > 0)){
				$this->mysqlclass->mysql_my_query("DELETE FROM `".$this->setupdata['table_prefix']."letters_emails_unsub` WHERE ".$elem." = `id`", __LINE__, __FILE__);		
			}
		}
	}
	
	function email_add_to_blacklist($email){
		$email = trim($email);
		if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email)){
			$sql = $this->mysqlclass->mysql_my_query("SELECT * FROM `".$this->setupdata['table_prefix']."letters_emails_unsub` WHERE `email`='".$email."'", __LINE__, __FILE__);
			if (mysql_num_rows($sql) == 0) {
				$sql = $this->mysqlclass->mysql_my_query("INSERT INTO `".$this->setupdata['table_prefix']."letters_emails_unsub` (`id`,`email`) VALUES ('', '".$email."')", __LINE__, __FILE__);
				return 0;
			} else return 14;
		} else return 13;
	}
	
	function send_form_to_mail($body_html, $body_text, $arr, $attachment="out"){
		if (isset($_SERVER['HTTP_REFERER']) && (strpos($_SERVER['HTTP_REFERER'], $this->setupdata['base_href']) !== false) && (strpos($_SERVER['HTTP_REFERER'], $this->setupdata['base_href']) == 0)){
		
			if (isset($this->setupdata['mail_separator'])) $m_sep = $this->setupdata['mail_separator'];
			else $m_sep = "\n";
			
			if (strlen($body_text) == 0) $body_text = " ";
			if (strlen($body_html) == 0) $body_html = " ";
			$un    = strtoupper(uniqid(time()));
			$arr['form_to'] = trim($arr['form_to']);
			$mail_array = preg_split("/[\s,;]+/", $arr['form_to'], -1, PREG_SPLIT_NO_EMPTY);
			if (count($mail_array) > 1){
				$arr['form_to'] = "";
				foreach($mail_array as $mail){
					if (preg_match('/^\".+\"\s\<[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}\>/i', $mail) || preg_match('/[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}/i', $mail)){
						$arr['form_to'] .= trim($mail).", ";
					}
				}
			}
			$arr['form_to'] = trim($arr['form_to']);
			if (substr($arr['form_to'], strlen($arr['form_to'])-1, 1) == ',') $arr['form_to'] = substr($arr['form_to'], 0, strlen($arr['form_to'])-1);
			if (!isset($arr['form_from'])) $arr['form_from'] = $_SERVER["SERVER_NAME"]."@".$_SERVER["SERVER_NAME"].".com";
			$head  = "From: ".$arr['form_from'].$m_sep; 
			$encoded = chunk_split(bin2hex($arr['form_subject']), 2, '='); 
			$encoded = "=".strtoupper(substr($encoded, 0, strlen($encoded) - 1));
			$arr['form_subject'] = '=?UTF-8?Q?'.$encoded.'?=';
			$head .= "Subject: ".$arr['form_subject'].$m_sep; 
			$head .= "Reply-To: ".$arr['form_from'].$m_sep; 
			$head .= "X-Mailer: JustPageIt Mailer 0.1".$m_sep; 
			$head .= "Mime-Version: 1.0".$m_sep; 

			$head .= "Content-Type: multipart/alternative; \n\tboundary=\"----=_NextPart_".$un."\"".$m_sep.$m_sep; 
			$body = "------=_NextPart_".$un.$m_sep."Content-type: text/plain; charset=\"utf-8\"".$m_sep."Content-Transfer-Encoding: base64".$m_sep.$m_sep; 
			$body_text = chunk_split(base64_encode($body_text), 76, $m_sep);
			$body_text .= $m_sep;
			$body .= $body_text; 
			
			$ids = array();
			$img_array = array();

			if ($attachment == "in"){
				$self_site = str_replace(":", "\:", $this->setupdata['base_href']);
				preg_match_all("'get.php\?.\.[0-9]+([0-9])'si", $body_html, $tmp);
				if (isset($tmp[0]) && is_array($tmp[0])){
					foreach($tmp[0] as $key=>$value){
						if (strpos($value, "get.php?i") !== false){
							$x = explode(".", $value);
							$ids[$x[intval(count($x)-1)]] = $value;
						}
					}
				}
				preg_match_all("'".$self_site."/(client/.*?[\.jpg][\.gif]+)'si", $body_html, $tmp);
				if (isset($tmp[1]) && is_array($tmp[1])){
					foreach($tmp[1] as $key=>$value) $img_array[$value] = $tmp[0][$key];
				}
			}

			if ((count($ids) > 0) || (count($img_array))){
				$un1   = strtoupper(uniqid(time()));
				$body .= "------=_NextPart_".$un.$m_sep."Content-Type: multipart/related;".$m_sep." boundary=\"----=_NextPart_".$un1."\"".$m_sep.$m_sep; 
				$body .= "------=_NextPart_".$un1.$m_sep."Content-Type: text/html; charset=\"utf-8\"".$m_sep."Content-Transfer-Encoding: base64".$m_sep.$m_sep; 

				foreach($ids as $key=>$value){
					$search = array("'".$self_site."/get.php\?i\.".$key.".*?\"'si", "'get.php\?i\.".$key.".*?\"'si");
					$replace = array("cid:part".$key.".".$un1."@".$_SERVER["SERVER_NAME"]."\"", "cid:part".$key.".".$un1."@".$_SERVER["SERVER_NAME"]."\"");
					$body_html = preg_replace($search, $replace, $body_html);
				}
				
				foreach($img_array as $key=>$value){
					$t4 = str_replace("/", "_", $key);
					$t4 = str_replace(".", "_", $t4);
					$img_array[$key] = $t4;
					$body_html = str_replace($value, "cid:".$t4, $body_html);
				}

				$body_html = chunk_split(base64_encode($body_html), 76, $m_sep);
				$body_html .= $m_sep;
				$body .= $body_html;

				global $fileclass;		
				
				foreach($img_array as $key=>$value){
					$scr = $key;
					if (!file_exists($scr) || is_dir($scr)){
						$scr = $this->setupdata['core_dir']."/design/img/no_image.jpg";
					}
					$t2 = explode("/", $key);
					$info['name'] = $t2[count($t2)-1];
					$info['size'] = filesize($scr);
					$t3 = getimagesize($scr);
					if (!isset($t3['mime'])){
							if ($t3[2] == 1) $info['mime'] = 'image/gif';
							elseif ($t3[2] == 2) $info['mime'] = 'image/jpeg';
              elseif ($t3[2] == 3) $info['mime'] = 'image/png';
              elseif ($t3[2] == 6) $info['mime'] = 'image/bmp';
					} else $info['mime'] = $t3['mime'];
					if (($info['size'] > '0')){
						$handle = fopen($scr, "rb"); 
						$body .= "------=_NextPart_".$un1.$m_sep;
						$body .= "Content-Type: ".$info['mime'].";".$m_sep." name=\"".$info['name']."\"".$m_sep; 
						$body .= "Content-Transfer-Encoding: base64".$m_sep; 
						$body .= "Content-ID: <".$value.">".$m_sep; 
						$body .= "Content-Disposition: inline;".$m_sep." filename=\"".basename($info['name'])."\"".$m_sep.$m_sep; 
						$body_file = chunk_split(base64_encode(fread($handle, $info['size'])), 76, $m_sep);
						$body_file .= $m_sep;
						$body .= $body_file;
						fclose($handle);
					}
				}

				foreach($ids as $key=>$value){
					$info = $fileclass->file_info($key, 'image');
					$scr = $this->setupdata['binary_path']."/".$info['link'];
					if (!(file_exists($scr))) {
						$scr = $this->setupdata['binary_path']."/".$info['parent'];
						$scr = $scr."/".$info['link'];
					}
					if (!file_exists($scr) || is_dir($scr)){
						$scr = $this->setupdata['core_dir']."/design/img/no_image.jpg";
					}
					$info['name'] = $info['link'];
					if (($info['size'] > '0')){
						$handle = fopen($scr, "rb"); 
						$body .= "------=_NextPart_".$un1.$m_sep;
						$body .= "Content-Type: ".$info['mime'].";".$m_sep." name=\"".$info['name']."\"".$m_sep; 
						$body .= "Content-Transfer-Encoding: base64".$m_sep; 
						$body .= "Content-ID: <part".$key.".".$un1."@".$_SERVER["SERVER_NAME"].">".$m_sep; 
						$body .= "Content-Disposition: inline;".$m_sep." filename=\"".basename($info['name'])."\"".$m_sep.$m_sep; 
						$body_file = chunk_split(base64_encode(fread($handle, $info['size'])), 76, $m_sep);
						$body_file .= $m_sep;
						$body .= $body_file;
						fclose($handle);
					}
				}
				
				$body .= "------=_NextPart_".$un1."--".$m_sep.$m_sep;
				$body .= "------=_NextPart_".$un."--".$m_sep;
			} else {
				# isjungiamas get.php nuorodos keitimas!
				#$search = array("'get.php'si");
				#$replace = array($this->setupdata['base_href']."/get.php");
				#$body_html = preg_replace($search, $replace, $body_html);
					
				$body .= "------=_NextPart_".$un.$m_sep."Content-Type: text/html; charset=\"utf-8\"".$m_sep."Content-Transfer-Encoding: base64".$m_sep.$m_sep; 
				$body_html = chunk_split(base64_encode($body_html), 76, $m_sep);
				$body_html .= $m_sep;
				$body .= $body_html;
				$body .= "------=_NextPart_".$un."--".$m_sep;
			}

			if (isset($arr['form_to']) && (strlen($arr['form_to'])>4)){
				$mass_to = explode(",", $arr['form_to']);
				if (is_array($mass_to) && (count($mass_to) > 0)){
					foreach($mass_to as $email) {
						$email = trim($email);
						$res = @mail($email, $arr['form_subject'], $body, $head); 
					}
				}
				return $res;
			} else $res = 0;
		} else {
			return 0;
		}
	}

}
?>
